<?php
namespace app\modules\api\models;

use yii;
use yii\db\Query;

class Income
{
    private $table;

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix.'income';
    }

    /**
     * 获取income列表
     * @param $p int 页数
     * @param $s int 大小
     * @param $where array搜索条件
     * @return array
     */
    public function income_list($p, $s, $where = [])
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if($where['pay_from']) {
            $db->andWhere(['pay_from'=>$where['pay_from']]);
        }
        if ($where['invocie_num']) {
            $db->andWhere(['invocie_num'=>$where['invocie_num']]);
        }
        if ($where['service_name']) {
            $db->andWhere(['service_name'=>$where['service_name']]);
        }
        if ($where['begin_time']) {
            $db->andWhere(['>=','date',$where['begin_time']]);
        }
        if ($where['end_time']) {
            $db->andWhere(['<=','date','end_time']);
        }
        if ($where['customer_name']) {
            $db->andWhere(['like','customer_name',$where['customer_name']]);
        }
        return $db->orderBy(['date'=>SORT_DESC,'serial_num'=>SORT_DESC])->offset(($p-1)*$s)->limit($s)->all();
    }

    /**
     * 获取income大小
     * @param $where array搜索条件
     * @return int
     */
    public function income_size($where = [])
    {
        $db = new Query();
        $db->select('count(*) as num')->from($this->table);
        $db->where(['split_status'=>1]);
        if($where['pay_from']) {
            $db->andWhere(['pay_from'=>$where['pay_from']]);
        }
        if ($where['invocie_num']) {
            $db->andWhere(['invocie_num'=>$where['invocie_num']]);
        }
        if ($where['service_name']) {
            $db->andWhere(['service_name'=>$where['service_name']]);
        }
        if ($where['begin_time']) {
            $db->andWhere(['>=','date',$where['begin_time']]);
        }
        if ($where['end_time']) {
            $db->andWhere(['<=','date','end_time']);
        }
        if ($where['customer_name']) {
            $db->andWhere(['like','customer_name',$where['customer_name']]);
        }
        $re = $db->one();
        return $re?$re['num']:0;
    }

    /**
     * 更新操作
     * @param array $data
     * @return bool
     */
    public function update($data)
    {
        $id = $data['id'];
        unset($data['id']);
        return  yii::$app->db->createCommand()->update($this->table, $data, ['id'=>$id])->execute();
    }
}
